package com.umeox.moto.mqtt;

import android.content.Context;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * 日期工具类
 */
public class DateUtils {
    public static final SimpleDateFormat SDF_YMD = new SimpleDateFormat("yyyy-MM-dd");
    public static final SimpleDateFormat SDF_YMDHMS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final SimpleDateFormat SDF_HM = new SimpleDateFormat("HH:mm");


    public static final long DAYS = TimeUnit.DAYS.toMillis(1L);
    public static final long HOUR = TimeUnit.HOURS.toMillis(1L);
    public static final long MINUTE = TimeUnit.MINUTES.toMillis(1L);

    /**
     * 获取时间HH:mm:ss
     *
     * @return
     */
    public static String getCurrentTime() {
        String time = null;
        String date = SDF_YMDHMS.format(new Date());
        //"\\s"以空格截断
        String[] split = date.split("\\s");
        if (split.length > 1) {
            time = split[1];
        }
        return time;
    }

    /**
     * 获取今天的时间戳，没有时分秒
     *
     * @return milliseconds since 1.1.1970 for today 0:00:00
     */
    public static int getTodayMillis() {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return (int) (c.getTimeInMillis() / 1000);
    }

    /**
     * 得到今天的日期
     *
     * @return
     */
    public static String getTodayDate() {
        return SDF_YMD.format(new Date());
    }

    /**
     * 得到明天的日期
     *
     * @return
     */
    public static String getTomorrowDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        return SDF_YMD.format(calendar.getTime());
    }


    /**
     * 判断是否大于当前时间
     *
     * @param time
     * @return
     */
    public static boolean judgeCurrTime(long time) {
        long round = System.currentTimeMillis();
        if (time - round > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取几天前
     *
     * @return
     */
    public static long fewDaysBeforeToday(long times) {
        return differentDays(System.currentTimeMillis(), times);
    }

    /**
     * end 比 start 多的天数
     *
     * @param start
     * @param end
     * @return
     */
    public static long differentDays(long start, long end) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTimeInMillis(start);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTimeInMillis(end);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) {
            //不同年
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                    //闰年
                    timeDistance += 366;
                } else {
                    //不是闰年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else {
            //同一年
            return day2 - day1;
        }
    }


    /**
     * 得到日期 yyyy-MM-dd
     *
     * @param time
     * @return
     */
    public static String formatDate(long time) {
        return SDF_YMD.format(time);
    }

    /**
     * 时间转化为时间(几点)
     *
     * @param time
     * @return
     */
    public static String formatTime(long time) {
        return SDF_HM.format(time);
    }

    /**
     * 得到日期 yyyy-MM-dd HH:mm
     *
     * @param time
     * @return
     */
    public static String formatDateTime(long time) {
        return SDF_YMDHMS.format(time);
    }

    /**
     * 时间转化为时间格式
     *
     * @param timeStamp
     * @return
     */
    public static String formatDateTime(long timeStamp, String... format) {
        SimpleDateFormat sdf = null;
        if (format != null && format.length > 0) {
            sdf = new SimpleDateFormat(format[0],Locale.getDefault());
        } else {
            sdf = SDF_YMDHMS;
        }
        return sdf.format(timeStamp);
    }

    /**
     * 将日期字符串转成时间戳
     *
     * @param dateStr 格式化日期字符串
     * @return
     */
    public static long formatDateToTime(String dateStr, String... format) {
        SimpleDateFormat sdf = null;
        if (format != null && format.length > 0) {
            sdf = new SimpleDateFormat(format[0], Locale.getDefault());
        } else {
            sdf = SDF_YMDHMS;
        }
        try {
            return sdf.parse(dateStr).getTime();
        } catch (ParseException e) {
            return -1;
        }
    }


    /**
     * 格式化时间, 根据传入的时间与当前时间对比，返回不同的格式字符串
     * 返回格式如 传入时间距当前时间小于一天，返回当天时间 05:30AM
     * 传入时间距当前时间大一天并且小于30天，返回当天时间 一天前
     * 传入时间距当前时间大一天并且大于30天，返回当天时间 一个月前
     * 传入时间距当前时间大一天并且大于一年，返回当天时间 一年前
     *
     * @param ctx     上下文
     * @param tagTime 时间戳
     */
    public static String intervalDate(Context ctx, long tagTime) {
        return "";
/*        if (tagTime <= 0) {
            return "";
        }

        Date date = new Date(tagTime);
        Calendar calTag = Calendar.getInstance();
        calTag.setTime(date);

        Calendar calNow = Calendar.getInstance();
        try {
            if (isSameDate(calTag, calNow)) {
                //0-上午；1-下午
                int ampm = calTag.get(Calendar.AM_PM);
                int hour = calTag.get(Calendar.HOUR);
                int minute = calTag.get(Calendar.MINUTE);
                return String.format(Locale.getDefault(), "%02d:%02d", hour, minute) + (ampm == Calendar.AM ? " AM" : " PM");
            } else {
                int quantity, identifier;
                if (isSameYear(calTag, calNow) && isSameMonth(calTag, calNow)) {
                    int dayNow = calNow.get(Calendar.DAY_OF_YEAR);
                    int dayTag = calTag.get(Calendar.DAY_OF_YEAR);
                    quantity = Math.abs(dayTag - dayNow);
                    identifier = R.plurals.number_of_day;
                    if (quantity == 1) {
                        int hour = calTag.get(Calendar.HOUR_OF_DAY);
                        int minute = calTag.get(Calendar.MINUTE);
                        Locale locale = ctx.getResources().getConfiguration().locale;
                        String language = locale.getLanguage();
                        boolean noQuantity = language.contains("zh")
                                || language.contains("vi")
                                || language.contains("th")
                                || language.contains("ja");
                        if (noQuantity) {
                            return ctx.getResources().getString(R.string.yesterday, hour, minute);
                        } else {
                            return ctx.getResources().getQuantityString(identifier, 1, hour, minute);
                        }
                    }
                } else if (isSameYear(calTag, calNow) && !isSameMonth(calTag, calNow)) {
                    int monthNow = calNow.get(Calendar.MONTH);
                    int monthTag = calTag.get(Calendar.MONTH);
                    quantity = Math.abs(monthTag - monthNow);
                    identifier = R.plurals.number_of_month;
                } else {
                    int yearNow = calNow.get(Calendar.YEAR);
                    int yearTag = calTag.get(Calendar.YEAR);
                    quantity = Math.abs(yearTag - yearNow);
                    identifier = R.plurals.number_of_year;
                }
                return ctx.getResources().getQuantityString(identifier, quantity, quantity);
            }
        } catch (Exception e) {
            return "";
        }*/
    }


    private static boolean isSameYear(Calendar tag, Calendar current) {
        return tag.get(Calendar.YEAR) == current.get(Calendar.YEAR);
    }

    private static boolean isSameMonth(Calendar tag, Calendar current) {
        return tag.get(Calendar.MONTH) == current.get(Calendar.MONTH);
    }

    private static boolean isSameDate(Calendar tag, Calendar current) {
        return isSameYear(tag, current) && isSameMonth(tag, current) && tag.get(Calendar.DAY_OF_MONTH) == current.get(Calendar.DAY_OF_MONTH);
    }


    private static SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    public static long getNextDayMillis() {
        final long nextDayMillis = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1);
        try {
            return mSimpleDateFormat.parse(mSimpleDateFormat.format(nextDayMillis)).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return nextDayMillis;
    }
}
